package com.yida.gwj.expend.handler;

import java.util.Optional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.yida.common.core.constant.SecurityConstants;
import com.yida.common.core.domain.R;
import com.yida.common.core.exception.ServiceException;
import com.yida.gwj.api.domain.GwjConfStep;
import com.yida.gwj.api.service.RemoteGwjConfigService;
import com.yida.gwj.common.enums.GwjBusinessLogResult;
import com.yida.gwj.common.utils.GwjEnumUtils;
import com.yida.gwj.expend.domain.GwjMaintenanceFundsBusiness;
import com.yida.gwj.expend.domain.GwjMaintenanceFundsBusinessLog;
import com.yida.gwj.expend.domain.dto.GetAttachmentInfoRequest;
import com.yida.gwj.expend.domain.message.MqBaseResult;
import com.yida.gwj.expend.domain.message.PreAcceptSecondSubmitMessage;
import com.yida.gwj.expend.domain.request.GwjMaintenanceFundsBusinessRequest;
import com.yida.gwj.expend.enums.BusinessAttachmentServerTypeEnum;
import com.yida.gwj.expend.enums.BusinessServerStatusEnum;
import com.yida.gwj.expend.enums.BusinessStatusEnum;
import com.yida.gwj.expend.enums.FlagStatusEnum;
import com.yida.gwj.expend.enums.MaintenanceFundsErrorEnum;
import com.yida.gwj.expend.service.IGwjMaintenanceFundsBusinessAttachmentService;
import com.yida.gwj.expend.service.IGwjMaintenanceFundsBusinessLogService;
import com.yida.gwj.expend.service.IGwjMaintenanceFundsBusinessService;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;

/**
 * 维修基金前服务处理程序
 *
 * @author liangp
 * @date 2023/04/10
 */
@Component
public class HandlerExpendPreService extends AbstractExpendPreService {

    private final static Logger log = LoggerFactory.getLogger(HandlerExpendPreService.class);
    private RemoteGwjConfigService remoteGwjConfigService;
    private IGwjMaintenanceFundsBusinessService maintenanceFundsBusinessService;
    private IGwjMaintenanceFundsBusinessLogService maintenanceFundsBusinessLogService;
    private IGwjMaintenanceFundsBusinessAttachmentService maintenanceFundsBusinessAttachmentService;

    public HandlerExpendPreService() {}

    public HandlerExpendPreService(RemoteGwjConfigService remoteGwjConfigService, IGwjMaintenanceFundsBusinessService maintenanceFundsBusinessService, IGwjMaintenanceFundsBusinessLogService maintenanceFundsBusinessLogService, IGwjMaintenanceFundsBusinessAttachmentService maintenanceFundsBusinessAttachmentService) {
        super(remoteGwjConfigService, maintenanceFundsBusinessService, maintenanceFundsBusinessLogService);
        this.remoteGwjConfigService = remoteGwjConfigService;
        this.maintenanceFundsBusinessService = maintenanceFundsBusinessService;
        this.maintenanceFundsBusinessLogService = maintenanceFundsBusinessLogService;
        this.maintenanceFundsBusinessAttachmentService = maintenanceFundsBusinessAttachmentService;
    }

    public void preAcceptSecondSubmit(MqBaseResult mqBaseResult) {
        PreAcceptSecondSubmitMessage preAcceptSecondSubmitMessage = JSONUtil.toBean(mqBaseResult.getJsonMsg(), PreAcceptSecondSubmitMessage.class);
        if (ObjectUtil.isNull(preAcceptSecondSubmitMessage)) {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.MQ_PRE_ACCEPT_SECOND_SUBMIT) + "JSON数据转换失败");
        }
        try {
            preAcceptSecondSubmitMessage.checkNull();
        } catch (Exception e) {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.MQ_PRE_ACCEPT_SECOND_SUBMIT) + e.getMessage());
        }
        GwjMaintenanceFundsBusiness maintenanceFundsBusiness = maintenanceFundsBusinessService.getGwjMaintenanceFundsBusiness(new GwjMaintenanceFundsBusinessRequest() {
            {
                setServerIdentification(preAcceptSecondSubmitMessage.getOutServerIdentification());
                setOutServerIdentification(preAcceptSecondSubmitMessage.getServerIdentification());
            }
        });
        Optional.ofNullable(maintenanceFundsBusiness).<ServiceException>orElseThrow(() -> {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.MQ_PRE_ACCEPT_SECOND_SUBMIT) + "公维金维修资金业务不能为空");
        });
        Optional.of(maintenanceFundsBusinessService.updateGwjMaintenanceFundsBusinessInner(new GwjMaintenanceFundsBusiness() {
            {
                if (ObjectUtil.notEqual(BusinessStatusEnum.RETREAT_PARTS.getCode(), maintenanceFundsBusiness.getStatus())) {
                    try {
                        R<GwjConfStep> r = remoteGwjConfigService.selectNextGwjConfStepByFlagId(maintenanceFundsBusiness.getBizFlagId(), maintenanceFundsBusiness.getStepId(), SecurityConstants.INNER);
                        if (R.isError(r)) {
                            throw new ServiceException(r.getMsg());
                        }
                        if (ObjectUtil.isNull(r.getData())) {
                            throw new ServiceException(r.getMsg());
                        }
                        setStepId(r.getData().getStepId());
                    } catch (Exception e) {
                        log.error("远程调用 -> [remoteGwjConfigService][selectNextGwjConfStepByFlagId]异常,异常信息: [{}]", e);
                        throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.MQ_PRE_ACCEPT_SECOND_SUBMIT) + "远程调用 -> [remoteGwjConfigService][selectNextGwjConfStepByFlagId]未获取到对应配置信息");
                    }
                } else {
                    // 删除二次补件信息
                    int deleteFlag = maintenanceFundsBusinessAttachmentService.deleteGwjMaintenanceFundsBusinessAttachment(new GetAttachmentInfoRequest() {
                        {
                            setServerIdentification(maintenanceFundsBusiness.getServerIdentification());
                            setServerTypeList(ListUtil.toList(BusinessAttachmentServerTypeEnum.PUBLICITY_PHOTOS.getCode(), BusinessAttachmentServerTypeEnum.APPLICANT_MATERIALS.getCode(), BusinessAttachmentServerTypeEnum.MAINTENANCE_CONTRACT.getCode(), BusinessAttachmentServerTypeEnum.ADVANCE_PAYMENT_RECEIPT.getCode(), BusinessAttachmentServerTypeEnum.APPLICATION_REPORT.getCode(),BusinessAttachmentServerTypeEnum.OWNER_COMMENTS.getCode(),BusinessAttachmentServerTypeEnum.OWNER_CONFIRMATION_CERTIFICATE.getCode()));
                        }
                    });
                }
                setStatus(BusinessStatusEnum.SUBMIT.getCode());
                setSupplementFlag(FlagStatusEnum.SUC.getCode());
                setServerStatus(BusinessServerStatusEnum.NORMAL.getCode());
                setBizId(maintenanceFundsBusiness.getBizId());
            }
        })).<ServiceException>orElseThrow(() -> {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.MQ_PRE_ACCEPT_SECOND_SUBMIT) + "公维金维修资金业务更新异常");
        });
        preAcceptSecondSubmitMessage.getMaintenanceFundsBusinessAttachmentList().forEach((attachment) -> {
            attachment.setServerIdentification(maintenanceFundsBusiness.getServerIdentification());
        });
        if (ObjectUtil.equal(maintenanceFundsBusinessAttachmentService.insertBatchAttachment(preAcceptSecondSubmitMessage.getMaintenanceFundsBusinessAttachmentList()), FlagStatusEnum.FAL.getCode())) {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.MQ_PRE_ACCEPT_SECOND_SUBMIT) + "上传材料失败");
        }
        int insertFlag = maintenanceFundsBusinessLogService.insertGwjMaintenanceFundsBusinessLog(new GwjMaintenanceFundsBusinessLog() {
            /**
             *
             */
            private static final long serialVersionUID = 1L;

            {
                setResult(GwjBusinessLogResult.SUBMIT.getCode());
                setBizId(maintenanceFundsBusiness.getBizId());
                setStepId(maintenanceFundsBusiness.getStepId());
                setOperId(maintenanceFundsBusiness.getApplicantUserId());
                setOperName(maintenanceFundsBusiness.getApplicantUserName());
            }
        });
        if (ObjectUtil.equal(FlagStatusEnum.FAL.getCode(), insertFlag)) {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.MQ_PRE_ACCEPT_SECOND_SUBMIT) + "新增签署意见GwjMaintenanceFundsBusinessLog失败");
        }
    }

}
